package com.example.apple.contextmenu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) findViewById(R.id.textview);

        //上下文菜单注册到控件里
        this.registerForContextMenu(textView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {

        //添加了图片的item
        menu.add(1,1,1,"主页").setIcon(R.drawable.e001);
        menu.add(1,2,2,"天气").setIcon(R.drawable.e001);
        menu.add(1,3,3,"趋势").setIcon(R.drawable.e001);
        menu.add(1,4,4,"工具").setIcon(R.drawable.e001);
        menu.add(1,5,5,"设置").setIcon(R.drawable.e001);
        return true;
    }

    //监听器
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        super.onOptionsItemSelected(item);
        switch(item.getItemId()) {
            case 1:
                Toast.makeText(this, "点击了‘" + item.getTitle() + "’菜单",
                        Toast.LENGTH_LONG).show();
                break;
            case 2:
                Toast.makeText(this, "点击了‘" + item.getTitle() + "’菜单",
                        Toast.LENGTH_LONG).show();
                break;
        }

        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater=this.getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId,menu);
    }

}